package cool.doudou.doudada.pay.config;

import cool.doudou.doudada.pay.core.api.WxPayApi;
import cool.doudou.doudada.pay.core.api.ZfbPayApi;
import cool.doudou.doudada.pay.core.processor.WxNotifyBeanPostProcessor;
import cool.doudou.doudada.pay.core.processor.ZfbNotifyBeanPostProcessor;
import cool.doudou.doudada.pay.core.util.CertificateUtil;
import cool.doudou.doudada.pay.properties.WxPayProperties;
import cool.doudou.doudada.pay.properties.ZfbPayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ObjectUtils;

/**
 * PayConfig
 *
 * @author jiangcs
 * @since 2022/2/20
 */
@Slf4j
public class PayConfig {
    @Bean
    public WxPayApi wxPayApi() {
        return new WxPayApi();
    }

    @Bean
    public ZfbPayApi zfbPayApi() {
        return new ZfbPayApi();
    }

    @Bean
    public WxNotifyBeanPostProcessor wxNotifyBeanPostProcessor() {
        return new WxNotifyBeanPostProcessor();
    }

    @Bean
    public ZfbNotifyBeanPostProcessor zfbNotifyBeanPostProcessor() {
        return new ZfbNotifyBeanPostProcessor();
    }

    @Autowired
    public void init(WxPayProperties wxPayProperties, ZfbPayProperties zfbPayProperties, WxPayApi wxPayApi) {
        if (wxPayProperties.getEnabled()) {
            if (ObjectUtils.isEmpty(wxPayProperties.getServerAddress()) || ObjectUtils.isEmpty(wxPayProperties.getAppId())
                    || ObjectUtils.isEmpty(wxPayProperties.getMchId()) || ObjectUtils.isEmpty(wxPayProperties.getPrivateKeyPath())
                    || ObjectUtils.isEmpty(wxPayProperties.getPrivateKeySerialNumber()) || ObjectUtils.isEmpty(wxPayProperties.getApiKeyV3())) {
                throw new RuntimeException("微信支付参数配置缺失");
            }

            try {
                // 加载微信商户密钥文件
                CertificateUtil.loadWxSecretKey(wxPayProperties.getPrivateKeyPath());
                // 加载微信平台证书
                wxPayApi.loadPlatformCertificate();
            } catch (Exception e) {
                log.error("加载微信密钥异常: ", e);
            }
        }

        if (zfbPayProperties.getEnabled()) {
            if (ObjectUtils.isEmpty(zfbPayProperties.getServerAddress()) || ObjectUtils.isEmpty(zfbPayProperties.getAppId())
                    || ObjectUtils.isEmpty(zfbPayProperties.getPrivateKeyPath()) || ObjectUtils.isEmpty(zfbPayProperties.getPublicKeyPath())) {
                throw new RuntimeException("支付宝支付参数配置缺失");
            }

            try {
                // 加载支付宝商户密钥文件
                CertificateUtil.loadZfbSecretKey(zfbPayProperties.getPrivateKeyPath(), zfbPayProperties.getPublicKeyPath());
            } catch (Exception e) {
                log.error("加载支付宝密钥异常: ", e);
            }
        }
    }
}
